package com.hmall.search.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.api.client.ItemClient;
import com.hmall.search.domain.dto.ItemDTO;
import com.hmall.search.domain.po.ItemDoc;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.IOException;

@RequiredArgsConstructor
public class SearchController {

    private final RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
            HttpHost.create("http://192.168.6.130:9200")
    ));

    private final ItemClient itemClient;

    @ApiOperation("搜索商品")
    @GetMapping("{id}")
    public ItemDTO search(@PathVariable("id") Long id) throws IOException {
        // 1.准备Request
        GetRequest request = new GetRequest("items", id.toString());
        // 2.发送请求
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 3.解析结果
        String item = response.getSourceAsString();

        ItemDoc itemDoc = JSONUtil.toBean(item, ItemDoc.class);

        ItemDTO itemDTO = BeanUtil.copyProperties(itemDoc, ItemDTO.class);

        return itemDTO;
    }
}
